package com.example.ssrbac.config;

import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.example.ssrbac.entity.Permission;
import com.example.ssrbac.entity.Role;
import com.example.ssrbac.entity.User;
import com.example.ssrbac.repository.PermissionRepository;
import com.example.ssrbac.repository.RoleRepository;
import com.example.ssrbac.repository.UserRepository;

/**
 * 数据初始化器
 * 在应用启动时自动创建基础数据，包括：
 * 1. 基础权限
 * 2. 基础角色
 * 3. 管理员用户
 */
@Component
public class DataInitializer implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) {
        logger.info("开始初始化基础数据...");

        // 创建基础权限
        logger.info("创建基础权限...");
        // 用户管理权限
        createPermissionIfNotExists("USER_READ", "查看用户", "/api/users", "GET");
        createPermissionIfNotExists("USER_CREATE", "创建用户", "/api/users", "POST");
        createPermissionIfNotExists("USER_UPDATE", "更新用户", "/api/users/{id}", "PUT");
        createPermissionIfNotExists("USER_DELETE", "删除用户", "/api/users/{id}", "DELETE");
        createPermissionIfNotExists("USER_ASSIGN_ROLES", "分配角色", "/api/users/{id}/roles", "POST");
        
        // 角色管理权限
        createPermissionIfNotExists("ROLE_READ", "查看角色", "/api/roles", "GET");
        createPermissionIfNotExists("ROLE_CREATE", "创建角色", "/api/roles", "POST");
        createPermissionIfNotExists("ROLE_UPDATE", "更新角色", "/api/roles/{id}", "PUT");
        createPermissionIfNotExists("ROLE_DELETE", "删除角色", "/api/roles/{id}", "DELETE");
        createPermissionIfNotExists("ROLE_ASSIGN_PERMISSIONS", "分配权限", "/api/roles/{id}/permissions", "POST");
        
        // 权限管理权限
        createPermissionIfNotExists("PERMISSION_READ", "查看权限", "/api/permissions", "GET");
        createPermissionIfNotExists("PERMISSION_CREATE", "创建权限", "/api/permissions", "POST");
        createPermissionIfNotExists("PERMISSION_UPDATE", "更新权限", "/api/permissions/{id}", "PUT");
        createPermissionIfNotExists("PERMISSION_DELETE", "删除权限", "/api/permissions/{id}", "DELETE");

        // 页面管理权限
        createPermissionIfNotExists("PAGE_READ", "查看页面", "/api/pages", "GET");
        createPermissionIfNotExists("PAGE_CREATE", "创建页面", "/api/pages", "POST");
        createPermissionIfNotExists("PAGE_UPDATE", "更新页面", "/api/pages/{id}", "PUT");
        createPermissionIfNotExists("PAGE_DELETE", "删除页面", "/api/pages/{id}", "DELETE");

        // 创建基础角色
        logger.info("创建基础角色...");
        Role adminRole = createRoleIfNotExists("ROLE_ADMIN", "管理员");
        Role userRole = createRoleIfNotExists("ROLE_USER", "普通用户");

        // 为管理员角色分配所有权限
        logger.info("为管理员角色分配权限...");
        Set<Permission> allPermissions = new HashSet<>(permissionRepository.findAll());
        adminRole.setPermissions(allPermissions);
        roleRepository.save(adminRole);

        // 为普通用户角色分配基本权限
        logger.info("为普通用户角色分配权限...");
        Set<Permission> userPermissions = new HashSet<>();
        permissionRepository.findByName("USER_READ").ifPresent(userPermissions::add);
        userRole.setPermissions(userPermissions);
        roleRepository.save(userRole);

        // 创建管理员用户
        logger.info("创建管理员用户...");
        createAdminUserIfNotExists(adminRole);
        
        logger.info("基础数据初始化完成！");
    }

    /**
     * 创建权限（如果不存在）
     * @param name 权限名称
     * @param description 权限描述
     * @param resource 资源路径
     * @param action HTTP方法
     */
    private void createPermissionIfNotExists(String name, String description, String resource, String action) {
        if (!permissionRepository.findByName(name).isPresent()) {
            logger.info("创建权限: {}", name);
            Permission permission = new Permission();
            permission.setName(name);
            permission.setDescription(description);
            permission.setResource(resource);
            permission.setAction(action);
            permissionRepository.save(permission);
        }
    }

    /**
     * 创建角色（如果不存在）
     * @param name 角色名称
     * @param description 角色描述
     * @return 创建或获取的角色对象
     */
    private Role createRoleIfNotExists(String name, String description) {
        return roleRepository.findByName(name)
                .orElseGet(() -> {
                    logger.info("创建角色: {}", name);
                    Role role = new Role();
                    role.setName(name);
                    role.setDescription(description);
                    return roleRepository.save(role);
                });
    }

    /**
     * 创建管理员用户（如果不存在）
     * @param adminRole 管理员角色
     */
    private void createAdminUserIfNotExists(Role adminRole) {
        if (!userRepository.findByUsername("admin").isPresent()) {
            logger.info("创建管理员用户");
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("admin123"));
            admin.setEmail("admin@example.com");
            admin.setEnabled(true);
            
            Set<Role> roles = new HashSet<>();
            roles.add(adminRole);
            admin.setRoles(roles);
            
            userRepository.save(admin);
        }
    }
} 